package binderipcremoteviews

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import android.os.Parcel
import android.widget.RemoteViews
import com.android.binderserverclient0.R
import com.android.binderserverclient0.TestRemoteViewActivity

class TranscationRemoteViewsService(context: Context) : Binder(), ITranscationRemoteViews {

    private val mContext = context

    init {
        attachInterface(this, ITranscationRemoteViews.TRANSCATION_REMOTE_VIEWS_DESCRIPTION)
    }

    override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
        when (code) {
            ITranscationRemoteViews.TRANSCATION_ADD_REMOTE_VIEWS -> {
                data.enforceInterface(ITranscationRemoteViews.TRANSCATION_REMOTE_VIEWS_DESCRIPTION)
                reply?.writeNoException()
                val remoteVies = addRemoteViews()
                reply?.writeValue(remoteVies)
                return true
            }
        }
        return super.onTransact(code, data, reply, flags)
    }

    override fun addRemoteViews(): RemoteViews? {
        val remoteViews = RemoteViews("com.android.binderserverclient0", R.layout.remote_views_layout)
        remoteViews.setTextViewText(R.id.tv_icon, "123456")
        remoteViews.setImageViewResource(R.id.iv_icon, R.mipmap.ic_launcher_round)
        val intent = Intent(mContext, TestRemoteViewActivity::class.java)
        //val flags = PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE
        val flags = PendingIntent.FLAG_UPDATE_CURRENT
        val pendingIntent =
            PendingIntent.getActivity(mContext, 0x00, intent, flags)
        remoteViews.setOnClickPendingIntent(R.id.iv_icon, pendingIntent)
        //remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.b12)
        //val mBmp = BitmapFactory.decodeResource(mContext.resources, R.drawable.b11)
        //remoteViews.setImageViewBitmap(R.id.iv_icon, mBmp)
        return remoteViews
    }

    override fun asBinder(): IBinder {
        return this
    }
}